package zrpcservice

import (
"znet/zrpc"
"errors"
"znet/glog"
"znet/zconf"
"znet/zconst"
)


type RpcServiceModule struct {
	ConfServer 				zconf.Service
	RpcServices map[string] *RpcServiceNode
	OnClientEvent 			OnClientEvent
}

func (this *RpcServiceModule)Init() {
	this.RpcServices = make(map[string]*RpcServiceNode)
}
func (this *RpcServiceModule)AddClient(cConf zconf.RpcService) bool{
	rpc,ok := this.RpcServices[cConf.Name]
	if ok{
		glog.Info(cConf.Name + "已经存在，关闭重新连接")
		rpc.Close()
		rpc = nil
		delete(this.RpcServices,cConf.Name)
	}
	node := &RpcServiceNode{
		ConfServer:this.ConfServer,
	}
	node.InitClient(cConf,this)
	this.RpcServices[cConf.Name] = node
	return true
}
// 转发出去
func (this *RpcServiceModule) OnConnectionSuccess(rpc *RpcServiceNode){
	if this.OnClientEvent != nil {
		this.OnClientEvent.OnConnectionSuccess(rpc)
	}
}
func (this *RpcServiceModule) OnConnectionFail(rpc *RpcServiceNode){
	if this.OnClientEvent != nil {
		this.OnClientEvent.OnConnectionFail(rpc)
	}
}
// 同步调用
func (this *RpcServiceModule)Call(rpcName string,cmd uint16,args interface{}) ( *zrpc.RpcArgsRes,error) {
	service,ok:= this.RpcServices[rpcName]
	if !ok{
		err := errors.New(rpcName + " " +"没有注册")
		glog.Error(err)
		return nil,err
	}
	r,err := service.Call(zconst.OnRpcMessage,zrpc.NewRpcArgsRes(cmd,args))
	if err != nil {
		glog.Error(err)
		return nil,err
	}
	rpcRes := zrpc.ReturnRpcArgsRes(r)
	if rpcRes.Error != ""{
		resErr := errors.New(rpcRes.Error)
		return rpcRes,resErr
	}
	return rpcRes,nil
}
func (this *RpcServiceModule)RegisterService(args *zrpc.RpcArgsRes) *zrpc.RpcArgsRes  {
	c := new(zconf.RpcService)
	args.DecodeData(c)
	res := args.NewRpcArgsRes()
	if c.Name == "" {
		res.EncodeData(false)
		res.Error = "Name 为空"
		return res
	}
	if c.Attr == "" {
		res.EncodeData(false)
		res.Error = "Attr 为空"
		return res
	}
	glog.Infof("收到注册请求：[%s](%s)" ,c.Name,c.Attr)
	if this.AddClient(*c) {
		res.EncodeData(true)
	}else{
		res.EncodeData(false)
	}
	return res
}
